/**
 * 二分法查找
 */
function binary_search(arr, low, high, key) {
  if (low > high) {
    return -1
  }

  var mid = parseInt((low + high) / 2)
  // 如果匹配到了就直接返回索引
  if (arr[mid] === key) {
    return mid
  } else if (arr[mid] > key) {
    high = mid - 1
    return binary_search(arr, low, high, key)
  } else {
    low = mid + 1
    return binary_search(arr, low, high, key)
  }
}

var arr = [1,2,3,4,5,6,7,8,9,10,11,23,44,86];
var result = binary_search(arr, 0, 13, 10);
// console.log(result)

/**
 * 二分法查找实现sqrt(x)求平方根实例：9输出3 4输出2 5输出2
 */
function sqrt(num) {
  if (num <= 0) return null;
  if (num === 1) return num;
  let value = parseInt(num / 2)
  console.log('sqrt---', value)
  if (value * value <= num) return value;
  return calcSqrt(num, 1, value)
}

function calcSqrt(num, min, max) {
  let mid = Math.floor((min + max) / 2)
  // if (mid === min) return min;
  if (mid === min) {
    return min
  } else if (mid * mid > num) {
    return calcSqrt(num, min, mid)
  } else if (mid * mid < num) {
    return calcSqrt(num, mid, max)
  } else {
    return mid
  }
}

console.log(sqrt(10))